/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

package org.apache.airavata.metcat.dispatcher;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.airavata.metcat.parser.EventNotificationParser;
import org.w3c.dom.Document;

public class Dispatcher implements Runnable {
	XPath xpath;
	DispatchQueue queue;
	EventMsgHandlerMap eventMsgHandlerMap;

	public Dispatcher() {
		init();
	}

	private void init() {
		XPathFactory xpathFactory = XPathFactory.newInstance();
		xpath = xpathFactory.newXPath();
		queue = DispatchQueue.getInstance();
		eventMsgHandlerMap = EventMsgHandlerMap.getInstance();
	}

	public void run() {
		while (true) {
			Document doc = queue.getMsgFromQueue();
			if (doc != null)
				dispatch(doc);
		}

	}

	private void dispatch(Document doc) {
		String eventType = getEventMessageType(doc);
		System.out.println(eventType);
		EventNotificationParser eventMsgHandler = eventMsgHandlerMap.getEventMsgHandler(eventType);
		if (eventMsgHandler == null)
			return;
		eventMsgHandler.refreshCache();
		try {
			eventMsgHandler.filterAndStore(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private String getEventMessageType(Document doc) {
		XPathExpression expr = null;
		String type = null;
		try {
			expr = xpath.compile("local-name(*)");
			type = (String) expr.evaluate(doc);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return type;
	}

}
